import axios, { AxiosError } from "axios";
import { apiUrl } from "./config";
import { toast } from "sonner";
import _ from "lodash";

// 创建axios实例
const axiosInstance = axios.create({
  baseURL: apiUrl,
  headers: {
    "Content-Type": "application/json",
  },
  withCredentials: true,
});

// 请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    const token = typeof window !== "undefined" ? localStorage.getItem("token") : null;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
      // set the header of Cache-Control { headers: {'Cache-Control': 'no-store'}}
      config.headers["Cache-Control"] = "no-store";
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

const handl401 =  _.debounce(() => {
  toast.error("登录过期，请重新登录");
  setTimeout(() => {
    window.location.href = "/admin";
  }, 3000);
}, 500);

// 响应拦截器
axiosInstance.interceptors.response.use(
  (response) => {
    // 处理成功响应
    return response;
  },
  (error) => {
    // 处理错误响应
    console.error("API请求失败:", error);
    if (error.response) {
      console.error("错误响应:", error.response.data);
      console.error("状态码:", error.response.status);
      if (error.response.status === 401) {
        handl401();
      }
    } else if (error instanceof AxiosError) {
      if (error.code === "ERR_NETWORK") {
        checkNetwork();
      } else return Promise.reject(error);
    } else return Promise.reject(error);
  }
);

async function checkNetwork() {
  try {
    await fetch("https://psstatic.cdn.bcebos.com/video/wiseindex/aa6eef91f8b5b1a33b454c401_1660835115000.png", { cache: "no-store" });
    toast.error("服务端可能出问题了，请联系老师");
  } catch (error) {
    toast.error("网络可能出问题了，请检查网络");
    console.error("网络可能出问题了", error);
  }
}

export default axiosInstance;
